<!--
 * @Description: 菜单管理-列表
 * @Author: xinqiao lxq1990.0716@qq.com
 * @Date: 2024-09-23
 * @LastEditors: xinqiao lxq1990.0716@qq.com
 * @LastEditTime: 2024-09-26
-->
<script lang="ts" setup>
  import { PlusOutlined } from '@ant-design/icons-vue'
  import { message, Modal } from 'ant-design-vue'
  import { onMounted, reactive } from 'vue'

  import { requestDelPermission, requestPermissionList } from '/@/api/system/ysys-user/permission'
  import { PermissionTypeDesc, PermissionTypeEnum } from '/@/api/system/ysys-user/permission/enum'
  import { HttpCodeEnum } from '/@/enums/httpEnum'
  import { useQueryPagination } from '/@/hooks/useQueryPagination'
  import { getModuleList } from '/@/storage'

  import Add from './components/Add.vue'
  import Edit from './components/Edit.vue'
  import InterfaceRelate from './components/InterfaceRelate.vue'

  /** 搜索条件 */
  const searchParam = reactive<PermissionListTypes.IRequest>({ moduleId: getModuleList()[0].moduleId, permissionName: '' })

  /** 表格列配置 */
  const columns = [
    { title: '名称', dataIndex: 'permissionName' },
    { title: '权重', dataIndex: 'permissionWeight' },
    { title: '类型', dataIndex: 'permissionType', customRender: ({ record }) => PermissionTypeDesc[record.permissionType] },
    { title: '操作', key: 'action' },
  ]

  const { loading, queryList, dataList, pagination, onPaginationChange, setQueryListCallback } = useQueryPagination<PermissionListTypes.IRequest, PermissionListTypes.IResponse[]>(searchParam, requestPermissionList)

  onMounted(() => {
    setQueryListCallback(deepSetKey)
    initData(1)
  })

  /**
   * 初始化数据
   * @param pageNum 当前页
   */
  const initData = async (pageNum?: number) => {
    if (!pageNum) await queryList()
    else await queryList({ current: pageNum })
  }

  /**
   * 递归设置数据源的key（a-table展开/收缩时需要）
   * @param childrens 子数据
   */
  const deepSetKey = (childrens: PermissionListTypes.IResponse[]) => {
    childrens.map((item: PermissionListTypes.IResponse & { key: number }) => {
      const { permissionId, children } = item
      item.key = permissionId
      if (children?.length > 0) deepSetKey(children)
    })
  }

  /**
   * 重置
   */
  const clear = () => (searchParam.permissionName = '')

  /**
   * 搜索
   */
  const search = async () => initData(1)

  /** 新增弹窗 */
  const modalAdd = reactive({
    visible: false,
    pId: NaN,
    pName: '',
    success: () => initData(1),
  })

  /**
   * 新增
   * @param pId 父id
   * @param pName 父名称
   */
  const add = (pId: number, pName: string) => {
    modalAdd.visible = true
    modalAdd.pId = pId
    modalAdd.pName = pName
  }

  /** 编辑弹窗 */
  const modalEdit = reactive({
    visible: false,
    permissionId: NaN,
    success: () => initData(),
  })

  /**
   * 编辑
   * @param record 角色
   */
  const edit = (record: PermissionListTypes.IResponse) => {
    modalEdit.visible = true
    modalEdit.permissionId = record.permissionId
  }

  /** 关联权限弹窗 */
  const modalInterfaceRelate = reactive({
    visible: false,
    permissionId: NaN,
    success: () => initData(),
  })

  /**
   * 关联接口
   * @param record 角色
   */
  const relateInterface = (record: PermissionListTypes.IResponse) => {
    modalInterfaceRelate.visible = true
    modalInterfaceRelate.permissionId = record.permissionId
  }

  /**
   * 删除
   * @param record 角色
   */
  const dele = (record: PermissionListTypes.IResponse) => {
    Modal.confirm({
      title: '删除',
      content: '确定删除该菜单吗？',
      onOk: async () => {
        const { responseCode } = await requestDelPermission({ permissionId: record.permissionId })
        if (responseCode === HttpCodeEnum.SUCCESS) {
          message.success('删除成功')
          initData()
        }
      },
    })
  }
</script>

<template>
  <div class="ssc-list menu-list">
    <div class="ssc-search">
      <a-row :gutter="24">
        <a-col :span="6">
          <a-form-item label="角色名称">
            <a-input v-model:value="searchParam.permissionName" :maxlength="20" placeholder="请输入" />
          </a-form-item>
        </a-col>
        <a-col :span="18">
          <a-row justify="end">
            <a-button @click="clear()">重置</a-button>
            <a-button class="ml-4" type="primary" @click="search()">查询</a-button>
          </a-row>
        </a-col>
      </a-row>
    </div>
    <div class="ssc-table">
      <div class="ssc-table-header">
        <span class="ssc-table-header-title">菜单管理</span>
        <a-button type="primary" @click="add(0, '')">
          <template #icon><plus-outlined :style="{ 'font-weight': 'bold' }" /></template>
          新建
        </a-button>
      </div>
      <a-table :columns="columns" :data-source="dataList" :loading="loading" :pagination="pagination" @change="onPaginationChange">
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'action'">
            <span>
              <template v-if="record.permissionType === PermissionTypeEnum.MENU">
                <a @click="add(record.permissionId, record.permissionName)">添加</a>
                <a-divider type="vertical" />
              </template>
              <a @click="edit(record)">编辑</a>
              <a-divider type="vertical" />
              <a @click="relateInterface(record)">关联接口</a>
              <template v-if="record.children.length === 0">
                <a-divider type="vertical" />
                <a class="color-error" @click="dele(record)">删除</a>
              </template>
            </span>
          </template>
        </template>
      </a-table>
    </div>
    <div class="modal">
      <Add v-model:visible="modalAdd.visible" :p-id="modalAdd.pId" :p-name="modalAdd.pName" @success="modalAdd.success" />
      <Edit v-model:visible="modalEdit.visible" :permission-id="modalEdit.permissionId" @success="modalEdit.success" />
      <InterfaceRelate v-model:visible="modalInterfaceRelate.visible" :permission-id="modalInterfaceRelate.permissionId" @success="modalInterfaceRelate.success" />
    </div>
  </div>
</template>

<style lang="less" scoped>
  .color-error {
    color: @error-color;
  }
</style>
